<template>
  <div v-if="shareType == 1 && show" @click="handleShow()" class="live_bg">
    <div class="wrapper">
        <img style="width: 100%; height: 100%;" :src="avatarUrl" alt="">
        <div class="glass"></div>
        <div class="section">
            <!-- <video v-if="version<`2.17.0`" controls="controls" id="playVideo" ref="playVideo" autoplay playsinline></video>
        <div v-else id="remoteVideo"></div> -->

            <div id="remoteVideo"></div>
        </div>
    </div>
  </div>
  <div v-else-if="shareType == 2">
    <div class="h5_video_bg">
        <div class="h5_section">
            <div class="h5_video" id="remoteVideo"></div>
        </div>
        <div v-if="!isPlay" class="placeholder_bg">
            <img style="width: 100%; height: 100%;" :src="avatarUrl" alt="">
            <div class="h5_glass"></div>
            <div class="play_icon_bg">
                <i @click="handlePlay()" style="font-size:80px; color: white" class="el-icon-video-play"></i>
            </div>
        </div>
    </div>
    <div v-if="isShowInfo" class="pay_info_bg">
        <div class="pay_info_content">
          <div style="display: flex; justify-content: center; margin-top: 35px;">
            <img class="pay_info_icon" :src="require('@/assets/front-img/info_icon.png')" alt="">
          </div>
          <div class="tips">试看结束，更多内容请下载“众茶通”APP</div>
          <div class="btn_bg">
            <div @click="handleDownload" class="confirm_pay_btn">去下载</div>
          </div>
          <div class="tips_bg">
            <div class="tips2">也可去小程序观看</div>
            <img class="wx_img" src="http://image.utea88.com/statics/zcgjgyl.jpg" alt="">
          </div>
        </div>
      </div>
  </div>
</template>

<script>
import { getLiveToken, getLiveinfo } from "@/api/Live";

export default {
  name: 'liveVideo',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
  },
  components: {
  },
  data() {
    return {
      appID: 1056092273,
      server: 'wss://webliveroom1056092273-api.imzego.com/ws',
      userID: '',
      roomID: '',//zcgj_wechat_roomID13312345972
      token: "",
      streamID: '',//zcgj_wechat_streamID13312345972
      playStreamID: '',
      zg: null,
      localStream: null,
      remoteStream: null,
      isLogin: false,
      videoCodec: 'H264',

      audioDeviceList:[],
      videoDeviceList:[],
      createSuccessSvgStatus:false,
      checkSystemRequireStatus:'',
      connectStatus:'DISCONNECTED',
      microphoneDevicesVal:null,
      cameraDevicesVal:'',
      cameraCheckStatus:true,
      microphoneCheckStatus:true,
      publishStreamStatus: false,
      videoCheckStatus:true,
      audioCheckStatus:true,
      playStreamStatus:false,
      mirrorVal:'none',
      publishInfoStreamID:'',
      playInfoStreamID:'',
      show: this.visible,
      avatarUrl: '',
      shareType: 1,//pc:1  H5:2 
      isShowInfo: false,
      liveInfo: {},
      isPlay: false
    }
  },
  watch: {
    visible(val) {
        this.show = val
    },
    show(val) {
      this.$emit('update:visible', val)
    }
  },
  methods:{
    async enumDevices(){
        const deviceInfo = await zg.enumDevices();
        this.audioDeviceList = deviceInfo &&
            deviceInfo.microphones.map((item, index) => {
                if (!item.deviceName) {
                    item.deviceName = 'microphone' + index;
                }
                console.log('microphone: ' + item.deviceName);
                return item;
            });
            this.audioDeviceList.push({deviceID:0,deviceName: '禁止'});
            this.microphoneDevicesVal = this.audioDeviceList[0].deviceID;
        this.videoDeviceList = deviceInfo &&
            deviceInfo.cameras.map((item, index) => {
                if (!item.deviceName) {
                    item.deviceName = 'camera' + index;
                }
                console.log('camera: ' + item.deviceName);
                return item;
            });
        this.videoDeviceList.push({deviceID:0,deviceName: '禁止'});
        this.cameraDevicesVal = this.videoDeviceList[0].deviceID;
    },
    initEvent() {
        zg.on('roomStateUpdate', (roomId, state) => {
            if (state === 'CONNECTED') {
                this.connectStatus = 'CONNECTED';
            }
            if (state === 'DISCONNECTED') {
                this.connectStatus = 'DISCONNECTED';
            }
        })

        zg.on('publisherStateUpdate', (result) => {
            if (result.state === 'PUBLISHING') {
                this.publishInfoStreamID = result.streamID;
            } else if (result.state === 'NO_PUBLISH') {
                this.publishInfoStreamID = "";
            }
        });

        zg.on('playerStateUpdate', (result) => {
            if (result.state === 'PLAYING') {
                this.playInfoStreamID = result.streamID;
            } else if (result.state === 'NO_PLAY') {
                this.playInfoStreamID = "";
            }
        });
    },
    // Step1 Create ZegoExpressEngine
    createZegoExpressEngine() {
        this.zg = new ZegoExpressEngine(this.appID, this.server);
        window.zg = this.zg;
    },
    // Step2 Check system requirements
    async checkSystemRequirements() {
        console.log('sdk version is', zg.getVersion());
        try {
            const result = await zg.checkSystemRequirements();

            console.warn('checkSystemRequirements ', result);

            if (!result.webRTC) {
                console.error('browser is not support webrtc!!');
                return false;
            } else if (!result.videoCodec.H264 && !result.videoCodec.VP8) {
                console.error('browser is not support H264 and VP8');
                return false;
            } else if (!result.camera && !result.microphones) {
                console.error('camera and microphones not allowed to use');
                return false;
            } else if (result.videoCodec.VP8) {
                if (!result.screenSharing) console.warn('browser is not support screenSharing');
            } else {
                console.log('不支持VP8，请前往混流转码测试');
            }
            return true;
        } catch (err) {
            console.error('checkSystemRequirements', err);
            return false;
        }
    },
    // Step3 Login room
    async loginRoom(roomId, userId, userName, token) {
        return await zg.loginRoom(roomId, token, {
            userID: userId,
            userName
        });
    }, 
    // Step4 Start Publishing Stream
    async startPublishingStream(streamId, config) {
        try {
            this.localStream = await zg.createStream(config);
            zg.startPublishingStream(streamId, this.localStream, { videoCodec:this.videoCodec });
            if (zg.getVersion()<"2.17.0") {
                this.$refs['publishVideo'].srcObject = this.localStream;
            } else {
                const localView = zg.createLocalStreamView(this.localStream)
                localView.play("localVideo", {
                    mirror: true,
                    objectFit: "cover",
                    enableAutoplayDialog: true,
                })
            }
            return true;
        } catch (err) {
            console.error('error',err);
            return false;
        }
    },
    // Step5 Start Play Stream
    async startPlayingStream(streamId, options = {}) {
        try {
            this.remoteStream = await zg.startPlayingStream(streamId, options);
            if (zg.getVersion() < "2.17.0") {
                this.$refs['playVideo'].srcObject = this.remoteStream;
            } else {
                const remoteView = zg.createRemoteStreamView(this.remoteStream);
                remoteView.play("remoteVideo", {
                    objectFit: "cover",
                    enableAutoplayDialog: true,
                })
            }

            if (this.shareType == 1) {
                let video = document.getElementsByTagName('video')[0]
                video.controls = true;
            }
            // setTimeout(() => {
            //   this.getPlayingStreamQuality(streamId)
            // }, 6000);
            
            return true;
        } catch (err) {
            return false;
        }
    },
    async getPlayingStreamQuality(streamId) {
        try {
            // this.res = await zg.getPlayingStreamQuality(streamId);
            
            return true;
        } catch (err) {
            return false;
        }
    },
    // Logout room
    logoutRoom(roomId){
        zg.logoutRoom(roomId);
    },
    // Stop Publishing Stream
    async stopPublishingStream(streamId) {
        zg.stopPublishingStream(streamId);
    },
    // Stop Play Stream
    async stopPlayingStream(streamId){
        zg.stopPlayingStream(streamId);
    },
    clearStream(){
        this.localStream && zg.destroyStream(this.localStream);
        this.localStream = null;
        this.remoteStream && zg.destroyStream(this.remoteStream);
        this.remoteStream = null;
        if(zg.getVersion() < "2.17.0"){
            this.$refs['publishVideo'].srcObject = null;
            this.$refs['playVideo'].srcObject = null;
        }
    },
    changeAudioDevices(){
        if(!zg || !this.localStream){
            return
        }
        const isMicrophoneMuted = zg.isMicrophoneMuted();
        if(!isNaN(this.microphoneDevicesVal) && !isMicrophoneMuted){
            zg.muteMicrophone(true);
        }else{
            zg.muteMicrophone(false);
            zg.useAudioDevice(this.localStream, this.microphoneDevicesVal);
        }
    },
    // ==============================================================
    // This part of the code binds the button click event
    // ==============================================================
    async createZegoExpressEngineOption(){
        if(!this.createSuccessSvgStatus) {
            this.createZegoExpressEngine();
            this.createSuccessSvgStatus = true;
            this.initEvent();
        }
    },
    async checkSystemRequire(){
        if (!this.zg) return alert('you should create zegoExpressEngine');
        const result = await this.checkSystemRequirements();
        if (result) {
            this.checkSystemRequireStatus = 'SUCCESS';
            this.enumDevices();
        } else {
            this.checkSystemRequireStatus = 'ERROR';
        }
    },
    async loginRoomOption(){
        try {
            this.isLogin =  await this.loginRoom(this.roomID, this.userID, this.userID, this.token);
        } catch (err) {
            this.isLogin = false;
            console.log(err);
        }
    },
    async startPublishing(){
        const flag = await this.startPublishingStream(this.streamID, {
            camera: {
                audioInput: this.microphoneDevicesVal,
                videoInput: this.cameraDevicesVal,
                video: this.cameraCheckStatus,
                audio: this.microphoneCheckStatus,
            }
        })
        if (flag) {
            this.publishStreamStatus = true;
        }
    },
    async startPlaying(){
        const flag = await this.startPlayingStream(this.playStreamID, {
            video: this.videoCheckStatus,
            audio: this.audioCheckStatus
        });
        if (flag) {
            this.playStreamStatus = true;
        }
    },
    async reset(){
        if(!this.zg){
            return
        }
        await this.stopPublishingStream(this.streamID);
        await this.stopPlayingStream(this.playStreamID);
        if (this.isLogin) {
            this.isLogin = false;
            this.logoutRoom(this.roomID);
        }
        this.clearStream();
        this.zg = null;
        window.zg = null;
        this.playStreamStatus = false;
        this.publishStreamStatus = false;
        this.createSuccessSvgStatus = false;
        this.checkSystemRequireStatus = '';
        this.audioCheckStatus = false;
    },
    async handleShow() {
        await this.reset()
        this.show = false
    },
    async start(mobile, token, userID, avatarUrl) {
        this.roomID = 'zcgj@roomID' + mobile;
        this.playStreamID = 'zcgj@streamID' + mobile;
        this.token = token
        this.userID = userID
        if (avatarUrl) {
            this.avatarUrl = avatarUrl
        }
        
        await this.reset()
        await this.createZegoExpressEngineOption()
        await this.loginRoomOption()
        this.startPlaying()
    },
    getInfo() {
        let videoId = this.$route.query.videoId
        getLiveinfo({ id: videoId }).then(response => {
            this.avatarUrl = response.avatarUrl
        }).catch(error => {
            console.log(error);
        })
    },
    handlePlay() {
        let videoId = this.$route.query.videoId
        getLiveinfo({ id: videoId }).then(response => { 
            if (response.status === 1) {
                this.isPlay = true
                let userID = Date.now().toString()
                let mobile = this.$route.query.mobile
                let roomID = 'zcgj@roomID' + mobile;
                this.playStreamID  = 'zcgj@streamID' + mobile;

                getLiveToken({ roomId: roomID, userId: userID}).then(response => { 
                    this.start(mobile, response, userID, '')
                    this.$nextTick(() => {
                        let list = document.querySelectorAll(".h5_video")
                        if (list && list.length > 0) {
                            list.forEach(video => {
                                video.style.width = this.$getViewportSize().width + 'px';
                                video.style.height = this.$getViewportSize().height + 'px';
                            });
                        }
                    })

                }).catch(error => {
                    console.log(error);
                })

                setTimeout(() => {
                    this.reset()
                    this.isPlay = false
                    this.isShowInfo = true
                }, 120000);
            } else {
                this.$message.error('直播已结束')
                this.reset()
                this.isPlay = false
                this.isShowInfo = true
            }
            
        }).catch(error => {
            console.log(error);
        })
    },
    handleDownload() {
        window.location.href = 'http://app.utea88.com/79821719089'
    }
  },
  computed: {
    version(){
        return this.zg?.getVersion() || 0
    }
  },
  created() {
    if (this.$route.query.shareType) {
        this.shareType = this.$route.query.shareType
    } else {
        this.shareType = 1
    }
    
    if (this.shareType == 2) {
        this.getInfo()
    }
  },
  mounted() {
    
  },
  beforeCreate() {},
  beforeMount() {},
  beforeUpdate() {},
  updated() {
    
  },
  beforeDestroy() {},
  destroyed() {},
  activated() {},
}
</script>

<style lang='scss' scoped>
    .live_bg {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
        background: rgba(0, 0, 0, 0.5);
	}

  .wrapper {
    position: absolute;
    // display: flex;
    // justify-content: center;
    // align-items: center;
    width: 1184px;
    height: 650px;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);

    .glass{
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        backdrop-filter: blur(5px);
    }
  }

  .section {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 360px;
    transform: translate(-50%, -50%);
  }

  .h5_video_bg {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: black;

    .h5_section {
        display: flex;
        justify-content: center;
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
    }

     .placeholder_bg {
        position: relative;
        width: 100%;
        height: 100%;

        .h5_glass{
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            backdrop-filter: blur(5px);
        }

        .play_icon_bg {
            display: flex;
            justify-content: center;
            align-items: center;
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
        }
    }
  }

  .pay_info_bg {
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    // background: rgba(0, 0, 0, 0.68);

    .pay_info_content {
        width: 263px;
        height: 480px;
        background: rgba(255, 255, 255, 1);
        border-radius: 12px;

        .pay_info_icon {
            width: 60px;
            height: 60px;
        }
    }

    .tips {
        margin-top: 30px;
        margin-left: 10px;
        width: calc(100% - 20px);
        height: 21px;
        font-size: 15px;
        font-weight: 400;
        color: rgba(170, 170, 170, 1);
        line-height: 21px;
        text-align: center;
    }

    .tips_bg {
        margin-top: 15px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        font-size: 15px;
        font-weight: 400;
        color: rgba(170, 170, 170, 1);
        line-height: 21px;
        .tips2 {
            text-align: center;
        }

        .wx_img {
            margin-top: 10px;
            margin-left: 30px;
            width: 200px;
            height: 200px;
        }
    }


    .btn_bg {
        margin-top: 35px;
        display: flex;
        width: 100%;
        justify-content: center;

        .confirm_pay_btn {
            width: 90px;
            height: 40px;
            color: rgba(255, 255, 255, 1);
            font-size: 16px;
            font-weight: 400;
            line-height: 40px;
            text-align: center;
            background: linear-gradient(90deg, rgba(255, 64, 108, 1) 0%, rgba(240, 19, 67, 1) 100%);
            box-shadow: 0px 2px 4px rgba(250, 44, 90, 0.3);
            border-radius: 30px;
            mix-blend-mode: normal;
        }
    }
  }
</style>